<template>
  <Dialog v-model="dialogVisible" title="功能室排期导入" width="400">
    <el-form
      ref="formRef"
      :model="uploadParam"
      :rules="formRules"
      v-loading="formLoading"
      label-width="auto"
      label-position="left"
    >
      <el-form-item label="所属园区" prop="schoolCode">
        <el-select v-model="uploadParam.schoolCode" placeholder="请选择所属园区" clearable>
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SCHOOL_CODE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划周" prop="weekId">
        <el-cascader
          class="w-full"
          v-model="uploadParam.weekId"
          :options="weekCascaderList"
          :props="cascaderProps"
          clearable
          filterable
          placeholder="请选择计划周"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="模板上传" required>
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          :action="importUrl"
          :auto-upload="false"
          :disabled="formLoading"
          :headers="uploadHeaders"
          :limit="1"
          :on-error="submitFormError"
          :on-exceed="handleExceed"
          :on-success="submitFormSuccess"
          :data="uploadParam"
          accept=".xlsx, .xls"
          drag
          class="w-full"
        >
          <Icon icon="ep:upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <!-- <div class="el-upload__tip">
            <el-checkbox v-model="updateSupport" />
            是否更新已经存在的用户数据
          </div> -->
              <span>仅允许导入 xls、xlsx 格式文件。</span>
              <el-link
                :underline="false"
                style="font-size: 12px; vertical-align: baseline"
                type="primary"
                href="https://file.gxys.pisakid.com/school/功能室排期导入模板.xlsx"
              >
                下载模板
              </el-link>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { getAccessToken, getTenantId } from '@/utils/auth'
import { RoomWeeksApi } from '@/api/school/room/weeks'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { defaultProps } from '@/utils/tree'
defineOptions({ name: 'SystemUserImportForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/school/room-reserve/import'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const updateSupport = ref(0) // 是否更新已经存在的用户数据
const uploadParam = reactive({
  weekId: '',
  schoolCode: ''
})
const weekCascaderList = ref([])
const cascaderProps: any = computed(() => {
  return {
    ...defaultProps,
    children: 'weeksList',
    label: 'weeksName',
    value: 'id'
  }
})
const roomType = ref('')
const formRef = ref()
const formRules = reactive({
  schoolCode: [{ required: true, message: '园区不能为空', trigger: 'blur' }],
  weekId: [{ required: true, message: '计划周不能为空', trigger: 'blur' }]
})
/** 打开弹窗 */
const open = (type) => {
  roomType.value = type
  dialogVisible.value = true
  updateSupport.value = 0
  fileList.value = []
  resetForm()
  getWeekCascaderList()
}
const getWeekCascaderList = async () => {
  try {
    const data = await RoomWeeksApi.getWeekScheduleList(roomType.value)
    if (data?.length) {
      data.forEach((item) => {
        item.weeksName = `${item.weekYear}年`
        item.id = item.weekYear
      })
    }
    weekCascaderList.value = data
  } catch (error) {
    console.log(error)
  }
}
const handleChange = async (value: any) => {}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  await formRef.value.validate()
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    uploadRef.value.clearFiles()
    message.error(response.msg)
    formLoading.value = false
    return
  }
  // 拼接提示语
  const data = response.data
  let text = '上传成功数量：' + data.createUsernames.length + ';'
  for (let username of data.createUsernames) {
    text += '< ' + username + ' >'
  }
  text += '更新成功数量：' + data.updateUsernames.length + ';'
  for (const username of data.updateUsernames) {
    text += '< ' + username + ' >'
  }
  text += '更新失败数量：' + Object.keys(data.failureUsernames).length + ';'
  for (const username in data.failureUsernames) {
    text += '< ' + username + ': ' + data.failureUsernames[username] + ' >'
  }
  message.alert(text)
  formLoading.value = false
  dialogVisible.value = false
  // 发送操作成功的事件
  emits('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = async (): Promise<void> => {
  // 重置上传状态和文件
  formLoading.value = false
  await nextTick()
  uploadRef.value?.clearFiles()
  formRef.value?.resetFields()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}
</script>
